/** * Create by mzq * Description: 病人信息录入弹框 * Date: 2025/2/12 16:18 *
Update: 2025/2/12 16:18 */

<template>
  <MyDiaLog
    :visible="visible"
    :titleName="'病人信息'"
    width="600px"
    @close="handleClose">
    <template>
      <div class="patient-info-content">
        <uni-forms
          :model="formData"
          ref="patientForm"
          label-width="100px">
          <uni-forms-item label="病人姓名:" name="name" label-align="right">
            <uni-easyinput
              v-model="formData.name"
              placeholder="请输入姓名"
              :styles="inputStyles" />
          </uni-forms-item>
          <uni-forms-item label="性别:" name="gender" label-align="right">
            <uni-data-select
              v-model="formData.gender"
              :localdata="genderOptions"
              placeholder="请选择性别"
              :clear="false" />
          </uni-forms-item>
          <uni-forms-item label="年龄:" name="age" label-align="right">
            <uni-easyinput
              v-model="formData.age"
              type="number"
              placeholder="请输入年龄"
              :styles="inputStyles" />
          </uni-forms-item>
          <uni-forms-item label="住院号:" name="hospitalNo" label-align="right">
            <uni-easyinput
              v-model="formData.hospitalNo"
              placeholder="请输入住院号"
              :styles="inputStyles" />
          </uni-forms-item>
          <uni-forms-item
            label="住院科室:"
            name="department"
            label-align="right">
            <uni-easyinput
              v-model="formData.department"
              placeholder="请输入住院科室"
              :styles="inputStyles" />
          </uni-forms-item>
          <uni-forms-item
            label="初步诊断:"
            name="diagnosis"
            label-align="right">
            <uni-easyinput
              v-model="formData.diagnosis"
              placeholder="请输入初步诊断"
              :styles="textareaStyles" />
          </uni-forms-item>
        </uni-forms>
        <view class="button-group">
          <div>
            <button class="uni-btn" @click="handleClose">取消</button>
          </div>
          <div>
            <button class="uni-btn uni-btn-primary" @click="handleSubmit">
              确定
            </button>
          </div>
        </view>
      </div>
    </template>
  </MyDiaLog>
</template>

<script>
import MyDiaLog from '@/components/MyDiaLog/MyDiaLog.vue'
import UniFormsItem from '@/uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue'
import UniDataSelect from '@/uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue'
import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue'
import { readJsonFromFile, writeJsonToFile, updateJsonById } from '@/utils/fileUtil'
import { mapState, mapMutations, mapActions } from 'vuex'
export default {
  name: 'PatientInformation',
  components: {
    UniEasyinput,
    UniDataSelect,
    UniFormsItem,
    MyDiaLog,
  },
  props: {
    /**
     * 控制弹框显示隐藏
     * @type {Boolean}
     * @default false
     */
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      formData: {
        name: '',
        gender: '',
        age: '',
        hospitalNo: '',
        department: '',
        diagnosis: '',
      },
      genderOptions: [
        { value: '男', text: '男' },
        { value: '女', text: '女' },
      ],
      inputStyles: {
        border: '1px solid #dcdfe6',
        borderRadius: '4px',
        padding: '0 10px',
      },
      textareaStyles: {
        border: '1px solid #dcdfe6',
        borderRadius: '4px',
        padding: '5px 10px',
        minHeight: '80px',
      },
      originalData: null,
      submitLock: false,
      lastPatientCache: null,
      lastReadTime: 0,
    }
  },
  methods: {
    ...mapMutations({
      setCurrentPatient: 'SET_CURRENT_PATIENT' // 假设你有这个mutation
    }),
    // 获取上一个患者信息
    getPatient() {
      const now = Date.now();
      if (this.lastPatientCache && (now - this.lastReadTime) < 300000) {
        this.setFormDataFromCache(this.lastPatientCache);
        return;
      }

      const res = readJsonFromFile('/sdcard/test/patient.json');
      if (res && Array.isArray(res) && res.length > 0) {
        const latestData = res[res.length - 1];
        this.lastPatientCache = latestData;
        this.lastReadTime = now;
        this.setFormDataFromCache(latestData);
      }
    },

    // 设置表单数据的辅助方法
    setFormDataFromCache(data) {
      this.originalData = data;
      this.formData = {
        name: data.name || '',
        gender: data.sex || '',
        age: data.age || '',
        hospitalNo: data.admissionNumber || '',
        department: data.Department || '',
        diagnosis: data.diagnosis || ''
      };
    },
    /**
     * 处理弹框关闭
     */
    handleClose() {
      this.$emit('close')
    },
    // 验证表单
    validateForm() {
      if (!this.formData.name) {
        uni.showToast({
          title: '请输入病人姓名',
          icon: 'none'
        })
        return false
      }
      if (!this.formData.gender) {
        uni.showToast({
          title: '请选择性别',
          icon: 'none'
        })
        return false
      }
      if (!this.formData.age) {
        uni.showToast({
          title: '请输入年龄',
          icon: 'none'
        })
        return false
      }
      if (!this.formData.hospitalNo) {
        uni.showToast({
          title: '请输入住院号',
          icon: 'none'
        })
        return false
      }
      if (!this.formData.department) {
        uni.showToast({
          title: '请输入住院科室',
          icon: 'none'
        })
        return false
      }
      if (!this.formData.diagnosis) {
        uni.showToast({
          title: '请输入初步诊断',
          icon: 'none'
        })
        return false
      }
      return true
    },
    handleSubmit() {
      if (this.submitLock) return;
      this.submitLock = true;

      if (this.validateForm()) {
        // 生成字符串格式的ID
        const timestamp = new Date().getTime();
        const randomNum = Math.floor(Math.random() * 10000);
        const stringId = `${timestamp}${randomNum}`;
        
        // 准备要保存的数据
        const saveData = {
          name: this.formData.name,
          sex: this.formData.gender,
          age: this.formData.age,
          admissionNumber: this.formData.hospitalNo,
          Department: this.formData.department,
          diagnosis: this.formData.diagnosis,
          operator: this.userInfo.username || 'sysadmin',
          id: stringId // 使用字符串格式的ID
        }

        try {
          // 1. 先存储到Vuex (如果有Vuex)
          if (this.setCurrentPatient) {
            this.setCurrentPatient(saveData);
          }
          
          // 2. 同时存储到全局变量
          if (getApp()) {
            getApp().globalData = getApp().globalData || {};
            getApp().globalData.currentPatient = saveData;
          }
          
          // 3. 关闭当前页面
          this.$emit('close');
          
          // 4. 立即跳转到监控页面
          uni.reLaunch({
            url: `/pages/monitor/monitor?patientId=${saveData.id}&fastMode=true`,
            success: () => {
              // 5. 跳转成功后再异步写入文件
              setTimeout(() => {
                writeJsonToFile(saveData, '/sdcard/test/patient.json');
              }, 500);
            }
          });
        } catch (error) {
          console.error('跳转失败:', error);
          // 如果跳转失败，回退到原始方法
          writeJsonToFile(saveData, '/sdcard/test/patient.json');
          uni.reLaunch({
            url: `/pages/monitor/monitor?patientId=${saveData.id}`,
          });
        }
      }
      
      setTimeout(() => {
        this.submitLock = false;
      }, 500);
    },
  },
  computed: {
    ...mapState(['userInfo']), // 添加 vuex 的 state 映射
  },
  mounted() {
    // 组件挂载完成后的处理逻辑
    this.getPatient()
  },
}
</script>

<style scoped lang="scss">
/* 病人信息内容区样式 */
.patient-info-content {
  padding: 20px;

  /deep/ .uni-forms-item {
    margin-bottom: 22px;

    .uni-forms-item__label {
      font-size: 14px;
      text-align: right !important;
      padding-right: 12px;
      box-sizing: border-box;
      width: 100px;
      justify-content: flex-end;
      display: flex;
    }
  }

  .button-group {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 10px;
    text-align: center;

    .uni-btn {
      margin: 0 10px;
      padding: 0 20px;
      height: 35px;
      line-height: 35px;
      font-size: 14px;
      border-radius: 4px;
      color: #000000;
      border: none;
      background: #E9E9E9;

      &.uni-btn-primary {
        background: #6DF7BE;
        border: none;
      }
    }
  }
}
</style>
